<template>
  <div class="guideInfo">
    <div class="add" style="text-align:right;">
      <el-button size="small" @click="handleAdd">添加导购</el-button>
    </div>
    <div class="tableList">
      <el-table :data="guide_list" style="width: 100%">
        <el-table-column prop="portrait" label="头像">
          <template slot-scope="scope">
            <img :src="scope.row.portrait" width="50" height="50"/>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="gender" label="性别" :formatter="formatSex"></el-table-column>
        <el-table-column prop="mobile" label="手机号码"></el-table-column>
        <el-table-column prop="created_at" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.$index, scope.row)" size="small">编辑</el-button>
            <el-button @click="handleDel(scope.$index, scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pageBox">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="pageChanged"
                     :current-page="currentPage"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="10"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!-- 编辑员工对话框 -->
    <el-dialog title="编辑" v-model="editFormVisible"
                           :close-on-click-modal="false"
                           :visible.sync="editFormVisible"
                           width="650px"
                           class="editForm">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入导购姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="avatar">
          <div class="txt">
            点击替换照片
          </div>
          <div class="imgwrapper" @click="uploadEditImg" :class="[editForm.change? 'hasImgFile' : '' ]">
            <img class="picture" :src="editForm.src || editForm.portrait" alt="" ref="editImg">
            <input type="file" accept="image/jpeg, image/jpg, image/png, image/bmp" @change="handleEditFile" class="hiddenInput editinput" style="display: none;"/>
          </div>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age" :min="0" :max="100" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="工作年限" prop="career">
          <el-input v-model="editForm.career" :min="0" :max="100" placeholder="请输入工作年限"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
    <!-- 增加员工表单 -->
    <el-dialog title="添加导购信息" v-model="addFormVisible"
                           :close-on-click-modal="false"
                           :visible.sync="addFormVisible"
                           width="650px"
                           class="addForm">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入导购姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addForm.gender">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="avatar">
          <div class="txt">
            添加照片
          </div>
          <div class="imgwrapper" @click="uploadAddImg" :class="[addForm.src? 'hasImgFile' : '' ]">
            <img class="picture" :src="addForm.src" alt="" ref="addImg">
            <i class="el-icon-circle-plus iconplus" :class="[addForm.src? 'hide' : 'show' ]"></i>
            <input type="file" accept="image/jpeg, image/jpg, image/png, image/bmp" @change="handleAddFile" class="hiddenInput addinput" style="display: none;"/>
          </div>
          <span class="imgError" v-if="imgError">图片不能为空</span>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addForm.age" :min="0" :max="100" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="工作年限" prop="career">
          <el-input v-model="addForm.career" :min="0" :max="100" placeholder="请输入工作年限"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  Table,
  TableColumn,
  MessageBox,
  Message,
  Pagination,
  Button,
  Form,
  Dialog,
  FormItem,
  Input,
  Radio,
  RadioGroup,
  Loading
} from 'element-ui'
import {
  APIGmallSalemans,
  APIGmallUpdateSalemans,
  APIGmallDeleteSalemans,
  APIGmallAddSalemans
} from '@/api/management.js'
import Exif from 'exif-js'
import config from '@/utils/config.js'
export default {
  name: 'guideinfo',
  data () {
    var checkAgeOfEditForm = (rule, value, callback) => {
      if (!value) {
        this.editForm.age = null
        callback()
        return this.editForm.age
      }
      var re = new RegExp(/^\d{1,}$/)
      if (!re.test(value)) {
        callback(new Error('年龄只能输入数字'))
      } else {
        if (value > 100) {
          callback(new Error('年龄不能超过100'))
        } else {
          callback()
        }
      }
    }
    var checkCareerOfEditForm = (rule, value, callback) => {
      if (!value) {
        this.editForm.career = null
        callback()
        return this.editForm.career
      }
      var re = new RegExp(/^\d{1,}$/)
      if (!re.test(value)) {
        callback(new Error('工作年限只能输入数字'))
      } else {
        if (value > 100) {
          callback(new Error('工作年限不能超过100'))
        } else {
          callback()
        }
      }
    }
    var checkAgeOfAddForm = (rule, value, callback) => {
      if (!value) {
        this.addForm.age = null
        callback()
        return this.addForm.age
      }
      var re = new RegExp(/^\d{1,}$/)
      if (!re.test(value)) {
        callback(new Error('年龄只能输入数字'))
      } else {
        if (value > 100) {
          callback(new Error('年龄不能超过100'))
        } else {
          callback()
        }
      }
    }
    var checkCareerOfAddForm = (rule, value, callback) => {
      if (!value) {
        this.addForm.career = null
        callback()
        return this.addForm.career
      }
      var re = new RegExp(/^\d{1,}$/)
      if (!re.test(value)) {
        callback(new Error('工作年限只能输入数字'))
      } else {
        if (value > 100) {
          callback(new Error('工作年限不能超过100'))
        } else {
          callback()
        }
      }
    }
    return {
      guide_list: [],
      last_page: '',
      current_page: 1,
      total: 0,
      config: config,
      // 编辑界面数据
      editForm: {},
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        },
        {
          max: 6,
          message: '姓名长度不能超过6位'
        }],
        mobile: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        },
        {
          max: 11,
          message: '手机号码长度不能超过11位'
        }],
        age: [
          { validator: checkAgeOfEditForm }
        ],
        career: [
          { validator: checkCareerOfEditForm }
        ]
      },
      formLabelWidth: '120px',
      currentPage: 1,
      currentPageSize: 10,
      // 编辑界面数据
      addForm: {
        shop: this.$store.getters.mallId,
        portrait: '',
        name: '',
        gender: '',
        mobile: '',
        age: '',
        career: '',
        src: ''
      },
      imgError: false,
      addFormVisible: false, // 编辑界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{
          required: true,
          message: '请输入导购姓名',
          trigger: 'blur'
        },
        {
          max: 6,
          message: '姓名长度不能超过6位'
        }],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          max: 11,
          message: '手机号码长度不能超过11位'
        }],
        age: [
          { validator: checkAgeOfAddForm }
        ],
        career: [
          { validator: checkCareerOfAddForm }
        ]
      }
    }
  },
  components: {
    elTable: Table,
    elTableColumn: TableColumn,
    elPagination: Pagination,
    elButton: Button,
    elForm: Form,
    elDialog: Dialog,
    elFormItem: FormItem,
    elInput: Input,
    elRadio: Radio,
    elRadioGroup: RadioGroup,
    elLoading: Loading
  },
  created () {
    this.GetSalemansInfo()
  },
  methods: {
    // 性别显示转换
    formatSex: function (row, column) {
      return row.gender === 1 ? '男' : '女'
    },
    // 获取导购列表
    GetSalemansInfo () {
      APIGmallSalemans({ shopId: this.$store.getters.mallId, page: this.currentPage, pagesize: this.currentPageSize })
        .then((res) => {
          let table = res.data.salemans.data
          this.guide_list = table
          this.total = res.data.salemans.total
        })
    },
    // 删除
    handleDel: function (index, row) {
      MessageBox.confirm('<strong>确认删除该导购人员？</strong><br><span style="float:left;font-size: 12px;margin-bottom: 20px;">导购人员删除后，所有的内容也将被立刻删除，不能恢复。</span>', '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        let para = { shopId: this.$store.getters.mallId, saleman: row.id }
        APIGmallDeleteSalemans(para).then((res) => {
          Message({
            message: '删除成功',
            type: 'success'
          })
          // 删除之后 重新读取 数据
          this.GetSalemansInfo()
        })
      })
    },
    // 显示编辑界面
    handleEdit: function (index, row) {
      this.editForm = Object.assign({src: '', imgFile: ''}, row)
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
      this.editFormVisible = true
    },
    // 编辑
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          MessageBox.confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            let para = this.editForm
            var formData = new FormData()
            if (this.editForm.imgFile) {
              formData.append('portrait', para.imgFile)
            }
            formData.append('_method', 'PUT')
            formData.append('name', para.name)
            formData.append('gender', para.gender)
            formData.append('mobile', para.mobile)
            formData.append('age', para.age ? para.age : 0)
            formData.append('career', para.career ? para.career : 0)
            APIGmallUpdateSalemans({ shopId: para.shop_id, saleman: para.id }, formData).then((res) => {
              this.editLoading = false
              Message({
                message: '该导购编辑信息已生效',
                type: 'success'
              })
              this.$refs['editForm'].resetFields()
              this.editFormVisible = false
              // 更新之后 重新读取 数据
              this.GetSalemansInfo()
            }).catch(() => {
              this.editLoading = false
            })
          })
        }
      })
    },
    // 显示增加导购界面
    handleAdd: function () {
      this.imgError = false
      this.addForm.portrait = ''
      this.addForm.name = ''
      this.addForm.gender = 1
      this.addForm.mobile = ''
      this.addForm.age = ''
      this.addForm.career = ''
      this.addForm.src = ''
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
        this.$el.querySelector('.addForm .imgwrapper').classList.remove('noImgFile')
      })
      this.addFormVisible = true
    },
    // 新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid && this.addForm.portrait) {
          this.$el.querySelector('.addForm .imgwrapper').classList.add('hasImgFile')
          MessageBox.confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            let para = this.addForm
            var formData = new FormData()
            formData.append('portrait', para.portrait)
            formData.append('name', para.name)
            formData.append('gender', para.gender)
            formData.append('mobile', para.mobile)
            formData.append('age', para.age ? para.age : 0)
            formData.append('career', para.career ? para.career : 0)
            APIGmallAddSalemans({ shopId: para.shop }, formData).then((res) => {
              this.addLoading = false
              Message({
                message: '提交成功',
                type: 'success'
              })
              this.$refs['addForm'].resetFields()
              this.addFormVisible = false
              this.GetSalemansInfo()
            }).catch(() => {
              this.addLoading = false
            })
          })
        } else if (!this.addForm.portrait) {
          this.imgError = true
          this.$el.querySelector('.addForm .imgwrapper').classList.add('noImgFile')
        }
      })
    },
    // 切换页面
    pageChanged (val) {
      this.currentPage = val
      this.GetSalemansInfo()
    },
    // 每页个数变化
    handleSizeChange (val) {
      this.currentPageSize = val
      this.GetSalemansInfo()
    },
    // 打开图片上传
    uploadEditImg (e) {
      this.$el.querySelector('.editinput').click()
    },
    uploadAddImg (e) {
      this.$el.querySelector('.addinput').click()
    },
    // 选择图片时上传和显示
    handleEditFile (e) {
      this.editForm.hasChanged = true
      let $target = e.target || e.srcElement
      let Orientation = null
      // 用户如果 点击 取消  则$target.files[0] 为 undefined
      if ($target.files[0]) {
        this.editForm.change = true
        this.editForm.imgFile = $target.files[0]
        let index = this.editForm.imgFile.name.lastIndexOf('.') + 1
        let ext = this.editForm.imgFile.name.substring(index)
        if ((/(jpg|jpeg|png|bmp)/i.test(ext))) {
          let reader = new FileReader()
          reader.onload = (data) => {
            let res = data.target || data.srcElement
            let img = new Image()
            img.src = res.result
            this.editForm.src = img.src
          }
          let that = this
          Exif.getData($target.files[0], function () {
            Exif.getAllTags(this)
            Orientation = Exif.getTag(this, 'Orientation')
            reader.readAsDataURL(that.editForm.imgFile)
            switch (Orientation) {
              case 6: // 旋转90度
                that.$refs['editImg'].style.transform = 'rotate(90deg)'
                break
              case 3: // 旋转180度
                that.$refs['editImg'].style.transform = 'rotate(180deg)'
                break
              case 8: // 旋转-90度
                that.$refs['editImg'].style.transform = 'rotate(-90deg)'
                break
              default:
            }
          })
        }
      }
    },
    handleAddFile (e) {
      let $target = e.target || e.srcElement
      let Orientation = null
      if ($target.files[0]) {
        this.imgError = false
        this.addForm.portrait = $target.files[0]
        let index = this.addForm.portrait.name.lastIndexOf('.') + 1
        let ext = this.addForm.portrait.name.substring(index)
        if ((/(jpg|jpeg|png|bmp)/i.test(ext))) {
          let reader = new FileReader()
          reader.onload = (data) => {
            let res = data.target || data.srcElement
            let img = new Image()
            img.src = res.result
            this.addForm.src = img.src
          }
          let that = this
          Exif.getData($target.files[0], function () {
            Exif.getAllTags(this)
            Orientation = Exif.getTag(this, 'Orientation')
            reader.readAsDataURL(that.addForm.portrait)
            switch (Orientation) {
              case 6: // 旋转90度
                that.$refs['addImg'].style.transform = 'rotate(90deg)'
                break
              case 3: // 旋转180度
                that.$refs['addImg'].style.transform = 'rotate(180deg)'
                break
              case 8: // 旋转-90度
                that.$refs['addImg'].style.transform = 'rotate(-90deg)'
                break
              default:
            }
          })
        }
      }
    }
  }
}
</script>

<style scoped lang="less" rel="stylesheet/less">
input[type="file"] {
  color: transparent;
}
.guideInfo {
  background-color: #ffffff;
  box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2);
  .add{
    padding: 10px 10px;
  }
  .pageBox {
      padding: 10px;
      text-align: right;
  }
  .editForm{
    .el-dialog__body{
      .el-form{
        .el-form-item{
          width: 50%;
        }
        .avatar{
          position: absolute;
          width:200px;
          height:200px;
          right: 140px;
          top: 140px;
          .txt{
            position: absolute;
            left: 0px;
            top: -35px;
            }
          .txt::before{
            content: '*';
            color: #f56c6c;
            margin-right: 4px;
          }
          .hasImgFile{
            border-color: #67c23a !important;
          }
          .noImgFile{
            border-color: #f56c6c !important;
          }
          .imgwrapper{
            position: absolute;
            width: 200px;
            height: 200px;
            border: 1px solid #c0ccda;
            .picture{
              width: 100%;
              height: 100%;
            }
            /* 隐藏的输入框 */
            .hiddenInput {
              position: absolute;
              width: 100%;
              height: 100%;
              left: 0;
              top: 0;
              opacity: 0;
              &:hover{
                color: transparent;
              }
            }
          }
          .imgError{
            position: absolute;
            top:200px;
            left:0;
            font-size: 12px;
            line-height: 1;
            padding-top: 4px;
            color: #f56c6c;
          }
        }
      }
    }
  }
  .addForm{
    .el-dialog{
      .el-dialog__body{
        .el-form{
          .el-form-item{
            width: 50%;
          }
          .avatar{
            position: absolute;
            width:200px;
            height:200px;
            right: 140px;
            top: 140px;
            .iconplus{
              position: absolute;
              left: 50%;
              top: 50%;
              transform: translate(-50%,-50%);
              font-size: 60px;
            }
            .show{
              display: block;
            }
            .hide{
              display: none;
            }
            .txt{
              position: absolute;
              left: 0px;
              top: -35px;
            }
            .txt::before{
              content: '*';
              color: #f56c6c;
              margin-right: 4px;
            }
            .hasImgFile{
              border-color: #67c23a !important;
            }
            .noImgFile{
              border-color: #f56c6c !important;
            }
            .imgwrapper{
              position: absolute;
              width: 200px;
              height: 200px;
              border: 1px dashed #c0ccda;
              .picture{
                width: 100%;
                height: 100%;
              }
              /* 隐藏的输入框 */
              .hiddenInput {
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
                opacity: 0;
              }
            }
            .imgError{
              position: absolute;
              top:200px;
              left:0;
              font-size: 12px;
              line-height: 1;
              padding-top: 4px;
              color: #f56c6c;
            }
          }
        }
      }
      .dialog-footer{
        text-align: center;
      }
    }
  }
}
</style>
